<?php

namespace app\service;

use app\exception\ErrnoPlus;
use share\service\BaseModelService;
use app\model\AppClientTableModel;
use share\exception\ApiException;

class AppClientTableService extends BaseModelService{

    public static function getModel()
    {
        return new AppClientTableModel;
    }
    

    public static function setRelationByAppInfo($appInfo,$appIds){
        $otherClients = OtherClientTableService::getAllByFilter([
            'app_id' => ['in', $appIds],
        ]);
        if(count($otherClients) != count($appIds)){
            throw new ApiException("other client info is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $vendor = $appInfo['vendor'];
        $relation = self::getAllByFilter([
            'vendor' => $vendor,
        ]);
        $relationOtherClientIds = array_column($relation,'aid');
        $delInfo = array_diff($relationOtherClientIds,$appIds);
        $addInfo = array_diff($appIds,$relationOtherClientIds);
        if(count($delInfo) > 0){
            self::delByFilter([
                'vendor' => $vendor,
                'aid' => ['in',$delInfo],
            ]);
        }
        if(count($addInfo) > 0){
            $items = [];
            $tn = time();
            foreach($addInfo as $aid){
                $items[] = [
                    'vendor' => $vendor,
                    'aid' => $aid,
                    'first_time' => $tn,
                    'modify_time' => $tn,
                ];
            }
            self::addBulk($items);
        }
        
    }

}